package com.mar.tech.unify.verticle.news;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.mar.tech.unify.RouterVerticle;
import com.mar.tech.unify.bean.ApiHandler;
import com.mar.tech.unify.bean.Result;
import com.mar.tech.unify.constants.QueueName;
import com.mar.tech.unify.service.database.DatabaseService;
import com.mar.tech.unify.verticle.BaseVerticle;
import com.wxapi.WxApiCall.WxApiCall;
import com.wxapi.model.RequestModel;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Description: 新闻 .<br>
 *
 * @author m-xy
 * @since 2019/9/4 13:54
 */
public class NewsVerticle extends BaseVerticle implements RouterVerticle {
  private final static Logger logger = LoggerFactory.getLogger(NewsVerticle.class);

  @Override
  public void start() throws Exception {
    super.start();
    databaseService = DatabaseService.createProxy(vertx, QueueName.DATABASE_QUEUE);
    ROUTERS.add(new ApiHandler(HttpMethod.GET, "/news/:keyword", this::queryNews));
    ROUTERS.add(new ApiHandler(HttpMethod.GET, "/news/es/:keyword", this::queryEsNews));
    vertx.eventBus().consumer("INFO", message -> {
      String keyword = String.valueOf(message.body());
      JsonArray list = jingdongNews(keyword);
      List<List<String>> rows = new ArrayList<>();
      rows.add(Arrays.asList(
        "标题", "线索分类", "线索领域", "来源ID", "来源名称", "发布人", "发布时间", "内容",
        "回复数量", "分享数量", "点赞数量", "阅读数量"
      ));
      for (Object o : list) {
        JsonObject oj = (JsonObject) o;
        String title = oj.getString("title", "default");
        String time = oj.getString("time", "default");
        String src = oj.getString("src", "default");
        String url = oj.getString("url", "default");
        String weburl = oj.getString("weburl", "default");
        String content = oj.getString("content", "default");
        String gallery = oj.getString("gallery", "default");
        Long addtime = oj.getLong("addtime", 0L);
        rows.add(Arrays.asList(
          title,
          String.valueOf(RandomUtil.randomInt(1, 3)),
          String.valueOf(RandomUtil.randomInt(1, 7)),
          String.valueOf(RandomUtil.randomInt(1000, 1003)),
          String.valueOf(src),
          gallery,
          time,
          content,
          String.valueOf(RandomUtil.randomInt(99, 1000)),
          String.valueOf(RandomUtil.randomInt(9, 1000)),
          String.valueOf(RandomUtil.randomInt(9, 1000)),
          String.valueOf(RandomUtil.randomInt(99, 1000))
        ));
      }
      //通过工具类创建writer
      ExcelWriter writer = ExcelUtil.getWriter(true);
      //一次性写出内容
      writer.write(rows);
      File file = new File(
        "/var/log/excel/".concat(keyword).concat("_").concat(LocalDateTime.now().toString()).concat(".xlsx")
      );
      writer.flush(file);
      //关闭writer，释放内存
      writer.close();
      message.reply(file.getPath());
    });

    vertx.eventBus().consumer("ES-INFO", message -> {
      String keyword = String.valueOf(message.body());
      JsonArray list = jingdongNews(keyword);
      long currentTimeMillis = System.currentTimeMillis();
      StringBuilder text = new StringBuilder();
      for (Object o : list) {
        JsonObject oj = (JsonObject) o;
        String title = oj.getString("title", "default");
        String time = oj.getString("time", "default");
        String src = oj.getString("src", "default");
        String url = oj.getString("url", "default");
        String weburl = oj.getString("weburl", "default");
        String content = oj.getString("content", "default");
        String gallery = oj.getString("gallery", "default");
        Long addtime = oj.getLong("addtime", 0L);
        JsonObject json = new JsonObject();
        text.append(new JsonObject().put("index", new JsonObject().put("_id", currentTimeMillis++)).toString());
        text.append("\n");
        json.put("content", content);
        json.put("title", title);
        json.put("author", "佚名");
        json.put("pubTime", time);
        text.append(json.toString());
        text.append("\n");
      }
      text.append("\n");
      vertx.fileSystem().open("excel/clue.json", new OpenOptions(),
        res -> {
          if (res.succeeded()) {
            AsyncFile file = res.result();
            file.write(Buffer.buffer(text.toString()), as -> {
              if (as.succeeded()) {
                logger.info("Written ok!");
                message.reply("excel/clue.json");
              } else {
                logger.error("Failed to write: ", as.cause());
                message.fail(1, as.cause().getMessage());
              }
            });
          } else {
            logger.error("Cannot open file ", res.cause());
            message.fail(1, res.cause().getMessage());
          }
        });
    });
  }

  private JsonArray jingdongNews(String keyword) {
    RequestModel model = new RequestModel();
    model.setGwUrl("https://way.jd.com/jisuapi/newSearch");
    model.setAppkey("27af8a293efe8f5e1aaaff274926d6c0");
    Map queryMap = new HashMap(1);
    queryMap.put("keyword", Optional.ofNullable(keyword).orElse("假冒"));
    model.setQueryParams(queryMap);
    WxApiCall call = new WxApiCall();
    call.setModel(model);
    String resp = call.request();
    JsonObject jsonObject = new JsonObject(resp);
    if (!"10000".equals(jsonObject.getString("code"))) {
      logger.error("返回异常:{}", resp);
      throw new RuntimeException(jsonObject.getString("msg"));
    }
    JsonObject result = jsonObject.getJsonObject("result", new JsonObject());
    if (!"ok".equals(result.getString("msg"))) {
      logger.error("返回异常:{}", resp);
      throw new RuntimeException(result.getString("msg"));
    }
    result = result.getJsonObject("result", new JsonObject());
    return result.getJsonArray("list", new JsonArray());
  }

  private void queryNews(RoutingContext routingContext) {
    String keyword = routingContext.request().getParam("keyword");
    vertx.eventBus().request("INFO", keyword, ar -> {
      if (ar.failed()) {
        Result.failed(routingContext, 404, ar.cause().getMessage());
        return;
      }
      routingContext.response().sendFile(ar.result().body().toString());
    });
  }

  private void queryEsNews(RoutingContext routingContext) {
    String keyword = routingContext.request().getParam("keyword");
    vertx.eventBus().request("ES-INFO", keyword, ar -> {
      if (ar.failed()) {
        Result.failed(routingContext, 404, ar.cause().getMessage());
        return;
      }
      routingContext.response().sendFile(ar.result().body().toString());
    });
  }
}
